package com.fcscs.ecms.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fcscs.ecms.dao.ECMSEntertainmentDynamicFieldDao;
import com.fcscs.ecms.dao.ECMSEntertainmentElmtsDao;
import com.fcscs.ecms.dao.ECMSEntertainmentMainDao;
import com.fcscs.ecms.dao.ECMSGlobalProprietaryInfoDao;
import com.fcscs.ecms.domain.GlobalProprietaryInfo;
import com.fcscs.ecms.domain.MdlEntertainmentDynamicField;
import com.fcscs.ecms.domain.MdlEntertainmentElmts;
import com.fcscs.ecms.domain.MdlEntertainmentMain;
import com.fcscs.ecms.service.ECMSEntertainmentManager;

/**
 * @author pvttinh
 * 
 */

@Service("ecmsEntertainmentManager")
public class ECMSEntertainmentManagerImpl implements ECMSEntertainmentManager {

	@Autowired
	ECMSEntertainmentMainDao ecmsEntertainmentMainDao;
	@Autowired
	ECMSEntertainmentElmtsDao ecmsEntertainmentElmtsDao;
	@Autowired
	ECMSEntertainmentDynamicFieldDao ecmsEntertainmentDynamicFieldDao;
	@Autowired
	ECMSGlobalProprietaryInfoDao ecmsGlobalProprietaryInfoDao;
	
	@Override
	public String getEntertainmentUrl(long moduleId, long orgId, long propId) throws Exception {
		// TODO Auto-generated method stub
		String entertainmentUrl = "";
		try{
			GlobalProprietaryInfo gpi = this.ecmsGlobalProprietaryInfoDao.find((int)orgId, (int)propId).get(0);
			
			MdlEntertainmentMain mem = this.ecmsEntertainmentMainDao.find((int)moduleId, gpi.getId()).get(0);
			entertainmentUrl += mem.getUrl() + "?";
			
			List<MdlEntertainmentElmts> meeList = this.ecmsEntertainmentElmtsDao.find(mem.getId(), mem.getProprietaryId());
			entertainmentUrl += this.getQueryString(meeList);
			entertainmentUrl.substring(0, entertainmentUrl.length()-1);
		}catch (Exception e) {
			// TODO: handle exception
			throw new Exception("Entertainment.MANAGER.getEntertainmentUrl() - " + e.getMessage());
		}
		
		return entertainmentUrl;
	}
	
	/**
	 * 
	 * @param meeList
	 * @return
	 * @throws Exception
	 */
	private String getQueryString(List<MdlEntertainmentElmts> meeList) throws Exception{
		
		String queryString = "";
		try{
			for(MdlEntertainmentElmts mee : meeList){
				if(mee.isIsActive()){
					String field = "";
					if((null == mee.getFieldName())||(mee.getFieldName().contains(" "))){
						MdlEntertainmentDynamicField medf = this.ecmsEntertainmentDynamicFieldDao.get(mee.getFieldId());
						field = medf.getDefaultName();
					}else{
						field = mee.getFieldName();
					}
					queryString += field + "=value&";
				}
			}
		}catch (Exception e) {
			// TODO: handle exception
			throw e;
		}
		
		return queryString;
	}
}
